﻿namespace WenAntdUI.Services
{
    public class DictService(IFreeSql freeSql)
    {
        private List<SysDict> dicts;

        public List<SysDict> Dicts => dicts ??= GetList();
        /// <summary>
        /// 获取字典列表
        /// </summary>
        /// <returns></returns>
        public List<SysDict> GetList()
        {
            return freeSql.Select<SysDict>().ToList();
        }
        /// <summary>
        /// 获取字典列表
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public List<SysDict> GetList(string category)
        {
            return Dicts.Where(w => w.Category == category).ToList();
        }

        /// <summary>
        /// 获取字典列表
        /// </summary>
        /// <param name="category"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public SysDict? Get(string category, string code)
        {
            return Dicts.FirstOrDefault(w => w.Category == category && w.Code == code);
        }

        /// <summary>
        /// 更新字典
        /// </summary>
        /// <param name="dict"></param>
        public void Update(SysDict dict)
        {
            freeSql.Update<SysDict>().SetSource(dict).ExecuteAffrows();
            dicts = null;
        }
        /// <summary>
        /// 删除字典
        /// </summary>
        /// <param name="dict"></param>
        public void Delete(SysDict dict)
        {
            freeSql.Delete<SysDict>().Where(w => w.Id == dict.Id).ExecuteAffrows();
            dicts = null;
        }
        /// <summary>
        /// 插入字典
        /// </summary>
        /// <param name="dict"></param>
        public void Insert(SysDict dict)
        {
            freeSql.Insert<SysDict>().AppendData(dict).ExecuteAffrows();
            dicts = null;
        }
        /// <summary>
        /// 刷新字典
        /// </summary>
        public void Refresh()
        {
            dicts = null;
        }
    }
}
